package cn.touna.jss.modules.third.bangsun;

import cn.touna.jss.common.properties.disconf.BangSunProperties;
import cn.touna.jss.common.util.BeanUtil;
import cn.touna.jss.common.util.HttpClientFactory;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.bangsun.entity.BangSunRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;


/**
 * 邦盛信贷风险名单查询
 */
@Service
public class BangSunService {

    private static final Logger LOG = LoggerFactory.getLogger(BangSunService.class);

    @Autowired
    private BangSunProperties bangSunProperties;


    @ApiMapping(value = "bangsun.loanRisk", desc = "邦盛.信贷风险名单查询")
    public Response loanRisk(BangSunRequestEntity requestEntity) {
        String address = bangSunProperties.getAddress();
        String name = requestEntity.getName();
        String idCard = requestEntity.getIdCard();

        //必要的参数校验
        if (StringUtils.isEmpty(address)) {
            return new Response().fail("1010", "请求地址为空");
        }
        if (StringUtils.isEmpty(name)) {
            return new Response().fail("1010", "未获取到姓名");
        }

        if (StringUtils.isEmpty(idCard)) {
            return new Response().fail("1010", "未获取到身份证号");
        }

        //url拼接
        String loanRiskUrl = bangSunProperties.getLoanRiskUrl();
        if (StringUtils.isEmpty(loanRiskUrl)) {
            return new Response().fail("1010", "url不合法");
        }

        Map<String, Object> map = BeanUtil.transBean2Map(requestEntity);
        //签名标签
        String date = String.valueOf(new Date().getTime());
        String param = param(map);
        String signature = loanRiskUrl + "\n" + param + "\n" + date;
        String validate = HmacUtils.hmacMd5Hex(bangSunProperties.getAppSecret().getBytes(), signature.getBytes(Charset.forName("UTF-8")));

        //url
        String url = url(address, loanRiskUrl, map);

        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClientFactory.getHttpClient();
            HttpGet httpGet = new HttpGet(url);
            //header
            httpGet.addHeader("X-BS-App-Key", bangSunProperties.getAppKey());
            httpGet.addHeader("X-BS-Date", date);
            httpGet.setHeader("X-BS-Validate", validate);
            response = httpClient.execute(httpGet);
            String body = EntityUtils.toString(response.getEntity(), "utf-8");

            LOG.info("body : {}", body);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return new Response().success(body);
            } else {
                JSONObject jsonObject = JSONObject.parseObject(body);
                return new Response().fail(jsonObject.getString("status"), jsonObject.getString("message"));
            }
        } catch (Exception e) {
            LOG.error("请求数据异常:{}", e);
            return new Response().fail("1101", e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.error("关闭response异常:{}", e);
                }
            }
        }
    }

    /**
     * 给出固定给事的请求参数，用于计算validate字段
     * 格式如:mobile=13000000000&idCard=431081198812261392&name=yuanfengfan"
     *
     * @param params
     * @return
     */
    private String param(Map<String, Object> params) {
        final StringBuilder sb = new StringBuilder();
        params.entrySet().stream().forEach(entry -> sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));
        String param = sb.toString();
        int index = param.lastIndexOf("&");
        param = param.substring(0, index);
        return param;
    }

    /**
     * 拼接url
     *
     * @param address:请求主机地址
     * @param url:业务查询path
     * @param params:业务查询参数
     * @return
     */
    private String url(String address, String url, Map<String, Object> params) {
        if (address.endsWith("/")) {
            address = address.substring(0, address.length() - 1);
        }
        int index = url.lastIndexOf("?");
        url = index < 0 ? url + "?" : url;
        StringBuilder sb = new StringBuilder(url);
        params.entrySet().stream().forEach(entry -> sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));
        url = sb.toString();
        index = url.lastIndexOf("&");
        url = url.substring(0, index);
        return address.concat(url);
    }
}
